package Dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import Entity.Event;
import mapper.Coursemapper;
import mapper.Eventmapper;
import mapper.Openexpmapper;

public class eventdao implements Eventmapper{
	private  static Eventmapper eventmapper;
	private  static SqlSession session;

	public eventdao() throws IOException {
	 	String resource ="mybatis-config.xml";
		InputStream inputstream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlsessionfactory = new SqlSessionFactoryBuilder().build(inputstream);
		 session = sqlsessionfactory.openSession();
        eventmapper = session.getMapper(Eventmapper.class);
    }
	public void close(){
		this.session.close();
	}
	@Override
	public boolean CreatEvent(Event event) {
		rankdao rm = null;
		try {
			rm = new rankdao();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int eid = rm.getNum("eid");
		event.setEid(String.valueOf(eid));
		Boolean iuser = this.eventmapper.CreatEvent(event);
		rm.UpdateNum("eid");
		if(iuser == true){
			session.commit();
		}else{
			session.rollback();
		}
		return iuser;
	}

	@Override
	public List<Event> eventQueryByDate(Date date) {
		
		List<Event> selectList = this.eventmapper.eventQueryByDate(date);

		return selectList;
	}

	@Override
	public List<Event> getAllEvent() {
		
		List<Event> selectList = this.eventmapper.getAllEvent();

		return selectList;
	}

	@Override
	public void delEvent(String eid) {
		
		
		this.eventmapper.delEvent(eid);
		session.commit();
		
	}

	@Override
	public List<Event> getAllEventBypage(int page) {
		Eventmapper em = null;
		try {
			em = new eventdao();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Event> ee = em.getAllEvent();
		//        从第几条数据开始
        int firstIndex = (page - 1) * 10;
        //	        到第几条数据结束
        int lastIndex = page * 10;
        if(lastIndex<=ee.size())
        	return ee.subList(firstIndex, lastIndex);
        else if(firstIndex>=ee.size())
        	return null;
        else
        	return ee.subList(firstIndex, ee.size());
	}
	
}
